import { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Space,
  Row,
  Col,
  Checkbox,
  Upload,
  Modal,
  Select,
  DatePicker,
} from 'antd';
import { useIntl } from 'umi';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import CateComp from '@/components/CategoryComponent';
import UploadUtil from '@/components/UploadUtil';
import request from '@/utils/request';
import moment from 'moment';

const { confirm } = Modal;
const apiURL = '/api/services/app/EventDetail/';
const apiURLMember = '/api/services/app/Members/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);
  const [fileList2, setFileList2] = useState<any[]>([]);
  const [record, setRecord] = useState<any>({});
  const [memberItems, setMemberItems] = useState<any[]>([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    const { record } = props;
    if (record) {
      getData(record.id);
      getMember();
    }
  }, [props.record]);

  const onFinish = (values: any) => {
    setLoading(true);
    let act = 'Update';
    if (values.model.id == 0 || !values.model.id) {
      act = 'New';
    }
    if (fileList) {
      const pics: any = [];
      fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.ProblemPic = pics.join(',');
    }
    if (fileList2) {
      const pics: any = [];
      fileList2.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.rectificationPic = pics.join(',');
    }
    request(`${apiURL}${act}`, {
      method: act == 'New' ? 'POST' : 'PUT',
      data: values.model,
    }).then((resp) => {
      if (resp.success) {
        message.success(intl.formatMessage({ id: 'pages.save.success' }));
        props.fetchDatas();
      }
      setLoading(false);
    });
  };

  const getMember = (kewords: string = '') => {
    request(apiURLMember + 'GetMembers', {
      method: 'Get',
      params: { kewords },
    }).then((response) => {
      const resp = response.result;
      setMemberItems(resp);
    });
  };

  const getData = (id: number) => {
    const fileList: any[] = [];
    const fileList2: any[] = [];
    setLoading(true);
    if (id) {
      request(`${apiURL}Get`, {
        method: 'GET',
        params: { id },
      }).then((resp) => {
        const result = resp.result;
        if (result.overTime) result.overTime = moment(result.overTime);
        if (result.problemPic) {
          const array = result.problemPic.split(',');
          array.forEach((item: string) => {
            fileList.push({
              uid: item,
              name: item + '.png',
              status: 'done',
              url: UploadUtil.getOssFile + item,
              thumbUrl: UploadUtil.getOssFile + item,
              response: { result: item },
            });
          });
        }
        if (result.rectificationPic) {
          const array = result.rectificationPic.split(',');
          array.forEach((item: string) => {
            fileList2.push({
              uid: item,
              name: item + '.png',
              status: 'done',
              url: UploadUtil.getOssFile + item,
              thumbUrl: UploadUtil.getOssFile + item,
              response: { result: item },
            });
          });
        }
        setRecord(result);
        setLoading(false);
        setFileList(fileList);
        setFileList2(fileList2);
        formRef.current.setFieldsValue({ model: result });
      });
    }
  };

  const handleDel = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(`${apiURL}Delete`, {
          method: 'DELETE',
          params: { Id: record.id },
        }).then((resp) => {
          if (resp.success) {
            message.success(intl.formatMessage({ id: 'pages.delete.success' }));
            props.fetchDatas();
            formRef.current.resetFields();
          }
        });
      },
      onCancel() {},
    });
  };

  const onClose = () => {
    props.closeDraw();
  };

  const handleUpload = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} ${intl.formatMessage({ id: 'pages.upload.success' })}`);
    }
    setFileList(info.fileList);
  };

  const handleUpload2 = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} ${intl.formatMessage({ id: 'pages.upload.success' })}`);
    }
    setFileList2(info.fileList);
  };

  const handleChange = (value: any) => {
    const obj = memberItems.filter((o: any) => o.id === value)[0];
    const result = formRef.current.getFieldsValue();
    result.approver = obj?.name;
    formRef.current.setFieldsValue({ model: result });
  };

  const optionMember = memberItems?.map((d: any) => (
    <Select.Option value={d.id} key={d.id}>
      {d.name}
    </Select.Option>
  ));

  return (
    <Form layout="vertical" ref={formRef} onFinish={onFinish}>
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Form.Item hidden name={['model', 'id']}>
            <Input />
          </Form.Item>
          <Form.Item hidden name={['model', 'problemPic']}>
            <Input />
          </Form.Item>
          <Form.Item hidden name={['model', 'rectificationPic']}>
            <Input />
          </Form.Item>
          <Form.Item hidden name={['model', 'merchId']}>
            <Input />
          </Form.Item>
          <Form.Item
            label={intl.formatMessage({ id: 'pages.eventTitle' })}
            name={['model', 'eventTitle']}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <CateComp
            layout="eventType"
            width={200}
            name={['model', 'eventType']}
            label={intl.formatMessage({ id: 'pages.eventType' })}
          />
          <Form.Item label={intl.formatMessage({ id: 'pages.submitter' })} name={['model', 'submitter']} rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.responsibleId' })} name={['model', 'responsibleId']}>
            <Select onChange={handleChange}>{optionMember}</Select>
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.problemText' })} name={['model', 'problemText']} rules={[{ required: true }]}>
            <Input.TextArea />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.problemPic' })} name={['model', 'problemPic']} hidden>
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.rectificationPic' })} name={['model', 'rectificationPic']} hidden>
            <Input />
          </Form.Item>
          <Form.Item>
            <Upload
              action={UploadUtil.uploadOSS}
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              data={{
                bucketName: 'oplugoss',
              }}
              multiple
              listType="picture"
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={UploadUtil.beforeUpload}
            >
              <Button type="default">{intl.formatMessage({ id: 'pages.problemPic' })}</Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Upload
              action={UploadUtil.uploadOSS}
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              multiple
              listType="picture"
              fileList={fileList2}
              onChange={handleUpload2}
              beforeUpload={UploadUtil.beforeUpload}
            >
              <Button type="default">{intl.formatMessage({ id: 'pages.rectificationPic' })}</Button>
            </Upload>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label={intl.formatMessage({ id: 'pages.eventNumber' })} name={['model', 'eventNumber']}>
            <Input disabled placeholder={intl.formatMessage({ id: 'pages.autoNumber' })} />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.memberId' })} name={['model', 'memberId']}>
            <Select>{optionMember}</Select>
          </Form.Item>
          <CateComp
            layout="eventStatus"
            width={120}
            name={['model', 'eventStatus']}
            label={intl.formatMessage({ id: 'pages.eventStatus' })}
          />
          <Form.Item label={intl.formatMessage({ id: 'pages.approver' })} name={['model', 'approver']}>
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.rectificationCon' })} name={['model', 'rectificationCon']}>
            <Input.TextArea />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.longitude' })} name={['model', 'longitude']} hidden>
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.latitude' })} name={['model', 'latitude']} hidden>
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.overTime' })} name={['model', 'overTime']}>
            <DatePicker />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.eventPlace' })} name={['model', 'eventPlace']}>
            <Input />
          </Form.Item>
          <Form.Item name={['model', 'rectification']} valuePropName="checked" hidden>
            <Checkbox>{intl.formatMessage({ id: 'pages.rectification' })}</Checkbox>
          </Form.Item>
        </Col>
      </Row>
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>
            {intl.formatMessage({ id: 'pages.save' })}
          </Button>
          <Button onClick={onClose}>{intl.formatMessage({ id: 'pages.cancel' })}</Button>
          <Button danger onClick={handleDel}>
            {intl.formatMessage({ id: 'pages.delete' })}
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default ViewPage;
